package com.hao.ui;

import com.hao.constants.CommonInfo;
import com.hao.service.EasyCopyService;
import com.hao.service.impl.EasyCopyServiceImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import org.apache.commons.lang.StringUtils;

import javax.swing.*;
import java.io.File;

public class SelectPath extends JDialog {

    private Project project;
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField pathSVN;
    private JTextField pathFileList;
    private JTextField pathOutPut;
    private JButton buttonChooseSVN;
    private JButton buttonChooseFileList;
    private JButton buttonChooseOutPutPath;

    private EasyCopyService easyCopyService;

    public SelectPath(Project project) {
        this.project = project;
        this.easyCopyService = EasyCopyServiceImpl.getInstance();
        init();
        setTitle(CommonInfo.TITLE);
        setContentPane(contentPane);
        setSize(500, 300);
        setModal(true);
    }

    /**
     * 打开窗口
     */
    public void open() {
        this.pack();
        setLocationRelativeTo(null);
        this.setVisible(true);
    }

    /**
     * 确定
     */
    private void onOK() {
        String msg = easyCopyService.easyCopy(pathSVN.getText(), pathFileList.getText(), pathOutPut.getText());
        if (StringUtils.isNotEmpty(msg)) {
            Messages.showWarningDialog(msg, "提示");
            return;
        }
        dispose();
    }

    /**
     * 取消
     */
    private void onCancel() {
        dispose();
    }

    /**
     * 文件目录选择
     * @param jTextField
     * @param fileSelectionMode
     */
    private void onChooseFilePath(JTextField jTextField,int fileSelectionMode) {
        JFileChooser chooser = new JFileChooser();
        chooser.setMultiSelectionEnabled(false);
        chooser.setFileSelectionMode(fileSelectionMode);// 设定只能选择到 1-目录，0-文件
        int state = chooser.showOpenDialog(getContentPane());// 此句是打开文件选择器界面的触发语句
        if (state == 1) {
            return;// 撤销则返回
        } else {
            File f = chooser.getSelectedFile();// f为选择到的文件
            jTextField.setText(f.getAbsolutePath());
        }
    }

    private void init() {
        buttonOK.addActionListener(e -> onOK());
        buttonCancel.addActionListener(e -> onCancel());
        buttonChooseSVN.addActionListener(e -> onChooseFilePath(pathSVN,1));
        buttonChooseFileList.addActionListener(e -> onChooseFilePath(pathFileList,0));
        buttonChooseOutPutPath.addActionListener(e -> onChooseFilePath(pathOutPut,1));
    }
}
